package com.blqy.fr.user.login;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.blqy.fr.account.client.UserBillFeignClient;
import com.blqy.fr.common.constant.RedisConstant;
import com.blqy.fr.common.execption.BlQyException;
import com.blqy.fr.common.result.ResultCodeEnum;
import com.blqy.fr.model.user.User;
import com.blqy.fr.user.mapper.UserMapper;
import com.blqy.fr.vo.user.UserVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Slf4j
@LoginBean(value = LoginType.EMAIL_LOGIN)
public class EmailLogin implements LoginInterface {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserBillFeignClient userBillFeignClient;
    @Override
    public Map<String, Object> login(LoginAccount account) {
        String email = account.getEmail();
        Integer inputCode = Integer.valueOf(account.getCode());

        // 1. 参数校验
        if (StringUtils.isBlank(email) || inputCode == null) {
            throw new BlQyException(ResultCodeEnum.PARAM_ERROR);
        }

        // 2. 从 Redis 获取验证码
        Integer storedCode = (Integer) redisTemplate.opsForValue().get(RedisConstant.EMAIL_CODE_KEY_PREFIX + email);
        if (storedCode == null) {
            throw new BlQyException(ResultCodeEnum.CODE_EXPIRED); // 验证码过期或未发送
        }

        // 3. 校验验证码
        if (!storedCode.equals(inputCode)) {
            throw new BlQyException(ResultCodeEnum.CODE_ERROR);
        }

        // 4. 查询用户
        User user = userMapper.selectOne(
                new LambdaQueryWrapper<User>()
                        .eq(User::getEmail, email)
        );


        // 5. 自动注册
        if (user == null) {
            user = new User();
            String string = UUID.randomUUID().toString();
            String replace = string.replace("-", "").substring(0, 8);
            user.setUserName("用户"+ replace);
            user.setEmail(email);
            user.setNickName("员工1" + redisTemplate.opsForValue().increment(RedisConstant.USER_NICKNAME_KEY));
            user.setAvatar("https://b0.bdstatic.com/ac1b7570f5eb5527a99a0997179662a4.jpg");
            user.setStatus(1);
            user.setRegisterTime(new Date());
            userMapper.insert(user);
            userBillFeignClient.init(user.getId());
            log.info("邮箱自动注册新用户，ID: {}, Email: {}", user.getId(), email);
        } else if (user.getStatus() == 0) {
            throw new BlQyException(ResultCodeEnum.ACCOUNT_DISABLED);
        }


        // 6. 生成 token
        String token = UUID.randomUUID().toString();

        // 7. 存入 Redis（✅ 改这里）
        UserVo userVo = new UserVo();
        BeanUtils.copyProperties(user, userVo);

        redisTemplate.opsForValue().set(
                RedisConstant.USER_LOGIN_KEY_PREFIX + token,
                userVo, // ✅ 存 JSON
                RedisConstant.USER_LOGIN_KEY_TIMEOUT,
                TimeUnit.SECONDS
        );

        // 8. 清除验证码
        redisTemplate.delete(RedisConstant.EMAIL_CODE_KEY_PREFIX + email);

        // 9. 更新最后登录时间
        user.setLastLoginTime(new Date());
        userMapper.updateById(user);

        // 10. 返回
        Map<String, Object> result = new HashMap<>();
        result.put("token", token);
        return result;
    }
}